const mongoose = require('mongoose');
const { Schoolmodel, userModel } = require('../model/model');

// 连接数据库
mongoose.connect('mongodb+srv://2305902315:XWpW0g8KLm20m7Ef@cluster0.v1royjo.mongodb.net/Promoted', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('数据库连接成功');
    createTestUser();
}).catch((err) => {
    console.log('数据库连接失败', err);
});

async function createTestUser() {
    try {
        // 首先查找武汉大学
        let whuSchool = await Schoolmodel.findOne({ name: '武汉大学' });
        
        // 如果武汉大学不存在，创建一个
        if (!whuSchool) {
            whuSchool = new Schoolmodel({
                name: '武汉大学',
                abbreviation: 'WHU',
                studentIdRule: {
                    pattern: '^WHU\\d{7}$',
                    minLength: 10,
                    maxLength: 10,
                    description: '请输入以WHU开头的10位学号'
                }
            });
            await whuSchool.save();
            console.log('武汉大学创建成功');
        }

        // 检查测试用户是否已存在
        const existingUser = await userModel.findById('507f1f77bcf86cd799439011');
        if (existingUser) {
            console.log('测试用户已存在');
            process.exit(0);
        }

        // 创建测试用户
        const testUser = new userModel({
            _id: new mongoose.Types.ObjectId('507f1f77bcf86cd799439011'),
            username: '测试用户',
            studentId: 'WHU2021001',
            schoolId: whuSchool._id,
            password: '123456',
            isAvatarImageSet: false,
            avatarImage: '',
            qianming: '这是一个测试用户',
            isTop: false,
            telp: 13800138000
        });

        await testUser.save();
        console.log('测试用户创建成功');
        console.log('用户ID:', testUser._id);
        console.log('用户名:', testUser.username);
        console.log('学号:', testUser.studentId);
        
        process.exit(0);
    } catch (error) {
        console.error('创建测试用户失败:', error);
        process.exit(1);
    }
}